﻿// -----------------------------------------------------------------------------
// 园丁,是个很简单的管理系统
//  gitee:https://gitee.com/hgflydream/Gardener 
//  issues:https://gitee.com/hgflydream/Gardener/issues 
// -----------------------------------------------------------------------------

using Gardener.Core.Common;
using Gardener.Core.Dtos;
using Gardener.Iot.Services;
using Gardener.Weighbridge.Impl.Entities;
using Gardener.Weighbridge.Services;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Gardener.Weighbridge.Impl.Services
{
    /// <summary>
    /// 地磅设备配置服务
    /// </summary>
    [ApiDescriptionSettings("Weighbridge", Module = "weighbridge")]
    public class WeighbridgeDeviceConfigService : ServiceBase<WeighbridgeDeviceConfig, WeighbridgeDeviceConfigDto, Int32, MasterDbContextLocator>, IWeighbridgeDeviceConfigService
    {
        private readonly IDeviceService deviceService;
        /// <summary>
        /// 地磅设备配置服务
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="deviceService"></param>
        public WeighbridgeDeviceConfigService(IRepository<WeighbridgeDeviceConfig, MasterDbContextLocator> repository, IDeviceService deviceService) : base(repository)
        {
            this.deviceService = deviceService;
        }

        /// <summary>
        /// 查询-获取多个设备配置信息
        /// </summary>
        /// <param name="deviceIds"></param>
        /// <returns></returns>
        public async Task<Dictionary<Guid, WeighbridgeDeviceConfigDto>> FindDeviceConfig(Guid[] deviceIds)
        {
            if (deviceIds == null || !deviceIds.Any())
            {
                return new();
            }
            List<WeighbridgeDeviceConfigDto> list = await _repository.AsQueryable(false).Where(x => deviceIds.Contains(x.DeviceId)).Select(x => x.Adapt<WeighbridgeDeviceConfigDto>()).ToListAsync();
            return list.ToDictionary(x => x.DeviceId, x => x);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <remarks>
        /// 高级查询，根据输入条件组合进行数据查询和排序
        /// </remarks>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async override Task<PageList<WeighbridgeDeviceConfigDto>> Search(PageRequest request)
        {
            PageList<WeighbridgeDeviceConfigDto> result = await base.Search(request);
            if (result.Items.Any())
            {
                foreach (var item in result.Items)
                {
                    item.Device = await deviceService.Find(item.DeviceId);
                }
            }
            return result;
        }
    }
}
